package com.suxin.algorithm.stack;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Tang
 * @classname CalculatorStack
 * @description [
 * 计算器 2+3*4+4/2-1
 * 1.求出后缀表达式
 * 2.顺序计算
 * ]
 * @date 2022/4/8 23:24
 */
public class CalculatorStack {

    private static Map<Character, Integer> map = new HashMap<>();

    MyStackByArray<Integer> intStack = new MyStackByArray<>(16);

    static {
        map.put('*', 4);
        map.put('/', 3);
        map.put('+', 2);
        map.put('-', 1);
    }

    public int calculatorExpression(String str) {
        String suffixExpression = getSuffixExpression(str);
        System.out.println("后缀表达式:" + suffixExpression);
        char[] chars = suffixExpression.toCharArray();
        // 顺序计算
        for (char ch : chars) {
            // 数字入栈
            if (!map.containsKey(ch)) {
                intStack.push(ch - '0');
                continue;
            }
            intStack.push(calculator(ch));
        }
        return intStack.pop();
    }

    int calculator(char ch) {
        // 符号计算
        Integer v1 = intStack.pop();
        Integer v2 = intStack.pop();

        switch (ch) {
            case '+':
                return v1 + v2;
            case '-':
                return v2 - v1;
            case '*':
                return v1 * v2;
            case '/':
                return v2 / v1;
            default:
                return 0;
        }
    }

    /**
     * 求解：后缀表达式
     * @param string
     * @return
     */
    private String getSuffixExpression(String string) {

        MyStackByArray<Character> symbolStack = new MyStackByArray<>(16);

        StringBuilder builder = new StringBuilder();
        char[] chars = string.toCharArray();
        for (char ch : chars) {
            // 数字直接追加
            if (!map.containsKey(ch)) {
                builder.append(ch);
                continue;
            }
            // 符号的话
            if (symbolStack.isEmpty()) {
                symbolStack.push(ch);
            } else {
                Character character = symbolStack.peek();
                // 弹出所有小于当前符号优先级的
                while (map.get(ch) < map.get(character) && ((character = symbolStack.pop()) != null)) {
                    builder.append(character);
                }
                // 把当前符号push进去
                symbolStack.push(ch);
            }
        }
        // 其余的直接追加到尾部
        while (!symbolStack.isEmpty()) {
            builder.append(symbolStack.pop());
        }
        return builder.toString();
    }

    public static void main(String[] args) {
        CalculatorStack calculatorStack = new CalculatorStack();
        System.out.println("计算结果为:--->" + calculatorStack.calculatorExpression("6+3*7-4+8/2"));
    }

}